import cors from 'cors'
import express from 'express'
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'
import setMorgan from './common/logs'
import setJwt from './server/jwt'
import setApis from './apis'
import setServer from './server'
import setConf from './common/conf'
// socket部分
import setSocket from './socket'

// create global app
const app = express()
// logs
setMorgan(app)
// conf
setConf(app)
// jwt
setJwt(app)
// cors
// app.use((req, res, next) => {
//   if (req.path !== '/' && !req.path.includes('.')) {
//     res.set({
//       'Access-Control-Allow-Credentials': true,
//       'Access-Control-Allow-Origin': req.headers.origin || '*',
//       'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
//       'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
//       'Content-Type': 'application/json; charset=utf-8'
//     })
//   }
//   req.method === 'OPTIONS' ? res.status(204).end() : next()
// })
app.use(
  cors({
    origin: ['http://localhost:3002'],
    optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
    credentials: true
  })
)
// env print
console.log(`NODE_ENV ==> ${process.env.NODE_ENV}, ${app.get('env')}`)
// parse cookes
app.use(cookieParser())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// apis
setApis(app)
// server
setServer(app)
// socket
setSocket()
